/**
 * Created by moyu on 2017/4/8.
 */

const getDb = require('./')
const collection = "article"

exports.add = function (data) {
    return getDb().then(db =>
        db.insertDocument(collection, data)
    );
};

exports.delete = function (data) {
    return getDb().then(db =>
        db.deleteOneDocument(collection, data)
    );
};

const find = exports.find = function (data, handle) {
    return getDb().then(db =>
        db.findDocuments(collection, data, handle)
    );
};

const findOne = exports.findOne = function (data, options) {
    return getDb().then(db =>
        db.findDocument(collection, data, options)
    );
};

const updateOne = exports.updateOne = function (data, options) {
    return new Promise((resolve, reject) => {
        get()
            .then(col => {
                col.updateOne(data, options, function (err, result) {
                    if (err) reject(err)
                    else if (result.matchedCount) {
                        resolve(result);
                    } else {
                        reject(result);
                    }
                })
            })
    })
};

exports.findSomeTags = function (count) {
    return new Promise((resolve, reject) => {
        get().then(col =>
            col.find({tags: /./}, {tags: 1}).toArray((err, list) => {
                if (err) {
                    reject(err)
                } else {
                    let map = list.reduce((map, n) => {
                        n.tags.forEach(name => {
                            map[name] = map[name] || 0;
                            map[name]++;
                        })
                        return map;
                    }, {});

                    let keys = Object.keys(map).sort((a, b) => map[b] - map[a]);
                    list = keys.slice(0, count).map(k => ({name: k, count: map[k]}))
                    resolve(list);
                }
            })
        )
    })
};

exports.recentArticles = function (count) {
    return new Promise((resolve, reject) => {
        get().then(col =>
            col
                .find({}, {title: 1})
                .sort({time: -1})
                .limit(count)
                .toArray((err, list) => {
                    if (err) {
                        reject(err)
                    } else {
                        resolve(list);
                    }
                })
        )
    })
};


const get = exports.get = function () {
    return getDb().then(db =>
        db.collection(collection)
    );
};

